package API.DAY10.socket.AI;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Client {
    private Socket socket;
    private PrintWriter toServer;
    private BufferedReader fromServer;
    private JTextArea chatArea;
    private JTextField inputField;

    public Client() {
        try {
            System.out.println("正在连接服务器...");
            socket = new Socket("172.40.140.113", 8088);
            System.out.println("连接服务器成功");

            // Initialize streams for communication with the server
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            toServer = new PrintWriter(bw, true);

            InputStream in = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
            fromServer = new BufferedReader(isr);

            // Start a thread to handle messages from the server
            ServerHandler handler = new ServerHandler();
            Thread t = new Thread(handler);
            t.setDaemon(true);
            t.start();

            // Create and show the GUI
            SwingUtilities.invokeLater(this::createAndShowGUI);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void createAndShowGUI() {
        JFrame frame = new JFrame("Chat Client");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.setLayout(new BorderLayout());

        // Create a text area for displaying messages
        chatArea = new JTextArea();
        chatArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(chatArea);
        frame.add(scrollPane, BorderLayout.CENTER);

        // Create a text field for user input
        inputField = new JTextField();
        frame.add(inputField, BorderLayout.SOUTH);

        // Add an action listener to send the message when Enter is pressed
        inputField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String message = inputField.getText();
                if (!message.trim().isEmpty()) {
                    toServer.println(message);
                    inputField.setText(""); // Clear the input field
                }
            }
        });

        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new Client();
    }

    public class ServerHandler implements Runnable {
        @Override
        public void run() {
            try {
                String message;
                while ((message = fromServer.readLine()) != null) {
                    String finalMessage = message;
                    SwingUtilities.invokeLater(() -> {
                        // Update the chat window with the received message
                        chatArea.append(finalMessage + "\n");
                    });
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}